#!/usr/bin/env python2
#-*- coding:utf-8 -*-
import smtplib
from email.MIMEText import MIMEText
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email import Encoders
import time
import os

BASEDIR = os.path.split(os.path.realpath(__file__))[0]


def sendmail(subject, contents, mail_from, mail_to, attach_path='', filename=''):
    # 构造MIMEMultipart对象做为根容器
    msg = MIMEMultipart()
    msg.attach(MIMEText(contents))
    # 如果有附件就将附件读取出来，添加到容器里面
    if attach_path != '' and filename != '':
        try:
            part = MIMEBase('application', 'octet-stream')
            #print attach_path + os.sep + filename
            part.set_payload(
                open(attach_path + os.sep + filename, 'rb').read())
            Encoders.encode_base64(part)
            part.add_header('Content-Disposition',
                            'attachment;filename="' + filename + '"')
            msg.attach(part)
        except Exception, e:
            print e

    msg['Subject'] = subject
    msg['From'] = mail_from
    msg['To'] = ';'.join(mail_to)
    #msg['date']=time.strftime('%Y-%m-%d %H:%M:%S')
    #msg['date']=time.strftime('%a, %d %b %Y %H:%M:%S %z')
    # 使用smtplib.SMTP模块来发送MIMEMultipart对象
    try:
        smtp = smtplib.SMTP()
        smtp.connect('localhost')
        smtp.sendmail(mail_from, mail_to, msg.as_string())
        smtp.quit()
        return True
    except Exception, e:
        print e
        return False


if __name__ == '__main__':
    subject = 'Hbase regions status ' + time.strftime("%Y%m%d%H%M%S")
    contents = 'Hbase regions rc-status'
    mail_from = 'no_reply@monitor.cn'
    mail_to = ['123@qq.com']
    from getHBaseTablesStatus import main
    filedir = main()
    attach_path = (os.sep).join(filedir.split('/')[:-1])
    filename = filedir.split('/')[-1]
    while not sendmail(subject, contents, mail_from, mail_to, attach_path, filename):
        print '邮件发送失败，2s后尝试重新发送'
        time.sleep(2)
    else:
        print "发送成功"
